<template>
  <el-card>
    <h2>续住管理</h2>
    <el-button type="primary" @click="openAdd">新增续住</el-button>
    <el-table :data="extensions" style="width: 100%;margin-top:16px">
      <el-table-column prop="extensionId" label="ID" width="60" />
      <el-table-column label="入住记录" width="120">
        <template #default="scope">
          {{ getCheckInInfo(scope.row.checkInId) }}
        </template>
      </el-table-column>
      <el-table-column label="原退房时间" width="170">
        <template #default="scope">
          {{ formatDate(scope.row.originalCheckOutDate) }}
        </template>
      </el-table-column>
      <el-table-column label="新退房时间" width="170">
        <template #default="scope">
          {{ formatDate(scope.row.newCheckOutDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="additionalDeposit" label="追加押金" width="100" />
      <el-table-column prop="reason" label="续住原因" />
      <el-table-column label="操作时间" width="150">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row.extensionId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="入住记录" prop="checkInId">
          <el-select v-model="form.checkInId" placeholder="请选择入住记录" style="width: 100%">
            <el-option 
              v-for="checkIn in activeCheckIns" 
              :key="checkIn.checkInId" 
              :label="`${getCustomerName(checkIn.customerId)} - ${getRoomNumber(checkIn.roomId)}`" 
              :value="checkIn.checkInId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原退房时间" prop="originalCheckOutDate">
          <el-date-picker 
            v-model="form.originalCheckOutDate" 
            type="datetime" 
            placeholder="选择原退房时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="新退房时间" prop="newCheckOutDate">
          <el-date-picker 
            v-model="form.newCheckOutDate" 
            type="datetime" 
            placeholder="选择新退房时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="追加押金" prop="additionalDeposit">
          <el-input v-model="form.additionalDeposit" type="number" placeholder="请输入追加押金金额" />
        </el-form-item>
        <el-form-item label="续住原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入续住原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getExtensions, addExtension, updateExtension, deleteExtension } from '../api/extension';
import { getCheckIns } from '../api/checkIn';
import { getCustomers } from '../api/customer';
import { getRooms } from '../api/room';
import { ElMessage, ElMessageBox } from 'element-plus';

const extensions = ref([]);
const checkIns = ref([]);
const customers = ref([]);
const rooms = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({ 
  extensionId: null, 
  checkInId: '', 
  userId: 1, // 默认操作员ID
  originalCheckOutDate: '', 
  newCheckOutDate: '', 
  additionalDeposit: '', 
  reason: '' 
});
const formRef = ref();

const rules = {
  checkInId: [{ required: true, message: '请选择入住记录', trigger: 'change' }],
  originalCheckOutDate: [{ required: true, message: '请选择原退房时间', trigger: 'change' }],
  newCheckOutDate: [{ required: true, message: '请选择新退房时间', trigger: 'change' }]
};

const loadExtensions = async () => {
  extensions.value = await getExtensions();
};

const loadCheckIns = async () => {
  checkIns.value = await getCheckIns();
};

const loadCustomers = async () => {
  customers.value = await getCustomers();
};

const loadRooms = async () => {
  rooms.value = await getRooms();
};

const getCheckInInfo = (checkInId) => {
  const checkIn = checkIns.value.find(c => c.checkInId === checkInId);
  if (!checkIn) return `入住${checkInId}`;
  const customer = customers.value.find(c => c.customerId === checkIn.customerId);
  const room = rooms.value.find(r => r.roomId === checkIn.roomId);
  return `${customer ? customer.fullName : '未知客户'} - ${room ? room.roomNumber : '未知房间'}`;
};

const getCustomerName = (customerId) => {
  const customer = customers.value.find(c => c.customerId === customerId);
  return customer ? customer.fullName : `客户${customerId}`;
};

const getRoomNumber = (roomId) => {
  const room = rooms.value.find(r => r.roomId === roomId);
  return room ? room.roomNumber : `房间${roomId}`;
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString();
};

const activeCheckIns = computed(() => {
  return checkIns.value.filter(checkIn => checkIn.status === 'active');
});

const openAdd = () => {
  dialogTitle.value = '新增续住';
  form.value = { 
    extensionId: null, 
    checkInId: '', 
    userId: 1, 
    originalCheckOutDate: '', 
    newCheckOutDate: '', 
    additionalDeposit: '', 
    reason: '' 
  };
  dialogVisible.value = true;
};

const openEdit = (row) => {
  dialogTitle.value = '编辑续住';
  form.value = { ...row };
  dialogVisible.value = true;
};

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!form.value.extensionId) {
      await addExtension(form.value);
      ElMessage.success('新增成功');
    } else {
      await updateExtension(form.value);
      ElMessage.success('修改成功');
    }
    dialogVisible.value = false;
    loadExtensions();
  });
};

const onDelete = (id) => {
  ElMessageBox.confirm('确定要删除该续住记录吗？', '提示', { type: 'warning' })
    .then(async () => {
      await deleteExtension(id);
      ElMessage.success('删除成功');
      loadExtensions();
    });
};

onMounted(() => {
  loadExtensions();
  loadCheckIns();
  loadCustomers();
  loadRooms();
});
</script> 